package io.renren.base;

import cn.hutool.http.HttpStatus;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @ClassName: R
 * @Description: 统一返回实体类
 * @Author: insanetz https://space.bilibili.com/602197686
 * @CreateDate: 2024/2/8 15:19
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class R<T> {

    @NonNull
    private int code;

    private String message;

    private String request;

    private T data;

    public static <V> R<V> success(V data) {
        HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
        R<V> response = new R<>();
        response.setCode(HttpStatus.HTTP_OK);
        response.setMessage("success");
        response.setData(data);
        response.setRequest(requestInfo(request));
        return response;
    }

    public static <V> R<V> success() {
        return success(null);
    }

    public static R<String> status(boolean status) {
        if (status) {
            return R.success("success");
        } else {
            return R.fail("fail");
        }
    }

    public static <V> R<V> fail(Integer code, String message, String request) {
        R<V> response = new R<>();
        response.setCode(code);
        response.setMessage(message);
        response.setRequest(request);
        return response;
    }

    public static <V> R<V> fail(String message) {
        R<V> response = new R<>();
        response.setCode(1000);
        response.setMessage(message);
        return response;
    }

    /**
     * 获取request的url字符串
     */
    public static String requestInfo(HttpServletRequest request) {
        String requestUrl = request.getRequestURI();
        String method = request.getMethod();
        return method + " " + requestUrl;
    }
}
